<template>
  <div class="new">
    <el-row style="margin-top: 16px">
      <el-col :span="4">
        <el-select
          v-model="meta.backGroundMusic"
          clearable
          placeholder="请选择背景音乐"
        >
          <el-option
            v-for="dict in backGroundMusicOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-col>

      <el-col :span="4">
        <el-select
          v-model="meta.TTSSpeaker"
          clearable
          placeholder="请选择语音讲述人"
        >
          <el-option
            v-for="dict in TTSSpeakerOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-col>

      <el-col :span="4">
        <el-form ref="meta" :model="meta" class="demo-ruleForm">
          <el-form-item
            label="  "
            prop="ttsType"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <el-select
              v-model="meta.ttsType"
              clearable
              placeholder="请选择资源"
              style="width: 87%"
            >
              <el-option
                v-for="dict in nlpList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="4">
        <el-input
          v-model.number="meta.ttsRate"
          placeholder="请输入语速"
          @blur="clickBlur()"
        />
      </el-col>
    </el-row>

    <div class="upload_contain">
      <el-upload
        ref="upload"
        multiple
        action="/textvideo/job-v2/multiTask"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :http-request="uploadFile"
        :auto-upload="false"
        name="fileZip"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 133px"
          size="small"
          type="success"
          :disabled="uploadIsShow"
          @click="submitUpload"
          >上传到服务器
        </el-button>
        <el-button
          type="primary"
          style="margin-left: 133px"
          size="small"
          @click="handleRefreh"
          >刷新</el-button
        >
        <div slot="tip" class="el-upload__tip">支持多文件上传(.txt)</div>
      </el-upload>
    </div>
    <ul>
      <li v-for="(item, key) in vedioList" :key="key">{{ key }}: {{ item }}</li>
    </ul>

    <div v-loading="loading" class="video-box">
      <video v-show="videoJob.videoUrl" :src="videoJob.videoUrl" controls />
    </div>
  </div>
</template>

<script>
import { service } from '@/utils/request'
const RESPONSE_CODE = {
  SUCCSS: 200,
  PROCESSING: 204,
  ERROR: 500,
  VIDEO_SUCCESS: '3',
  VIDEO_FAILD: '4'
}
export default {
  data() {
    return {
      loading: false,
      myHeaders: {
        'Content-Type':
          'multipart/form-data; boundary=<calculated when request is sent>'
      },
      backGroundMusicOptions: [],
      TTSSpeakerOptions: [],
      nlpList: [],
      uploadIsShow: false,
      meta: {
        title: '',
        content: '',
        processCode: 0,
        process: 0,
        taskId: '',
        response: '',
        rollTimeoutIndex: null,
        backGroundMusic: '',
        TTSSpeaker: '',
        ttsRate: '',
        ttsType: ''
      },
      videoJob: {
        code: null,
        width: 1920,
        height: 1080,
        status: '',
        videoUrl: '',
        rollTimeoutIndex: null
      },
      vedioList: {},
      url: '',
      fileData: '', // 文件上传数据（多文件合一）
      fileList: [], // upload多文件数组
      uploadData: {
        fieldData: {
          id: '' // 机构id,
        }
      },
      refrehList: []
    }
  },

  watch: {
    'videoJob.videoUrl': function() {
      this.loading = false
    }
  },

  created() {
    this.getDicts('fastvideo_bgm').then(response => {
      this.backGroundMusicOptions = response.data
    })

    this.getDicts('fastvideo_tts_speaker').then(response => {
      this.TTSSpeakerOptions = response.data
    })

    this.getDicts('nlp_search').then(response => {
      this.nlpList = response.data
    })
  },

  methods: {
    clickBlur() {
      if (!Number.isInteger(this.meta.ttsRate)) {
        this.$message.error('请输入数字值!')
        this.meta.ttsRate = ''
        return
      }

      if (this.meta.ttsRate < -500 || this.meta.ttsRate > 500) {
        this.$message.error('请输入语速值在-500到500之间!')
        this.meta.ttsRate = ''
        return
      }
    },

    handleRemove(file, fileList) {},

    handlePreview(file) {},

    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },

    uploadFile(file) {
      this.fileData.append('files', file.file) // append增加数据
    },

    handleRefreh() {
      if (this.url === '') {
        this.$message.error('暂无提交任务!')
        return
      }
      this.vedioList = {}
      service
        .get(`/textvideo/job-v2/multiTaskProgress/${this.url}`)
        .then(res => {
          const { data } = res
          this.vedioList = data
        })
    },

    // 上传到服务器
    submitUpload() {
      this.$refs.meta.validate(valid => {
        if (valid) {
          this.uploadIsShow = true
          this.vedioList = {}
          // const fieldData = this.uploadData.fieldData  // 缓存，注意，fieldData不要与fileData看混
          const isLt100M = this.fileList.every(
            file => file.size / 1024 / 1024 < 100
          )
          if (!isLt100M) {
            this.$message.error('请检查，上传文件大小不能超过100MB!')
          } else {
            this.fileData = new FormData() // new formData对象
            this.$refs.upload.submit() // 提交调用uploadFile函数
            this.fileData.append('backup3', this.meta.backGroundMusic)
            this.fileData.append('ttsSpeaker', this.meta.TTSSpeaker)
            this.fileData.append('ttsRate', this.meta.ttsRate)
            this.fileData.append('ttsType', this.meta.ttsType)
            service
              .post('/textvideo/job-v2/multiTask', this.fileData)
              .then(response => {
                console.log(response)
                if (response.code === 200) {
                  this.$message({
                    message: '上传成功',
                    type: 'success'
                  })

                  if (response.data && response.data.length > 0) {
                    this.refrehList = response.data
                    this.url = ''
                    response.data.map((item, index) => {
                      if (index === response.data.length - 1) {
                        this.url += item
                        service
                          .get(
                            `/textvideo/job-v2/multiTaskProgress/${this.url}`
                          )
                          .then(res => {
                            const { data } = res
                            this.vedioList = data
                            console.log(data.length, data, typeof data)
                          })
                      } else {
                        this.url += item + ','
                      }
                    })
                  }
                  this.fileList = []
                } else {
                  this.$message({
                    message: response.msg,
                    type: 'error'
                  })
                }
              })
              .finally(() => {
                this.uploadIsShow = false
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    submit(width, height) {
      this.videoJob.width = width
      this.videoJob.height = height

      clearInterval(this.meta.rollTimeoutIndex)
      this.meta.rollTimeoutIndex = null
      clearInterval(this.videoJob.rollTimeoutIndex)
      this.videoJob.rollTimeoutIndex = null

      this.loading = true
      service
        .post('/textvideo/job-v2/commit', {
          title: this.meta.title,
          content: this.meta.content
        })
        .then(res => {
          if (res.code === RESPONSE_CODE.SUCCSS) {
            this.meta.taskId = res.data.taskId
            this.rollSchedule()
          }
          if (res.code === RESPONSE_CODE.ERROR) {
            this._errorTip('任务提交失败')
          }
        })
        .catch(() => {})
    },

    _errorTip(text) {
      this.$notify.error({
        title: '错误',
        message: text
      })
      this.loading = false
    },

    schedule(taskId) {
      service
        .get(`/textvideo/job-v2/progress/${taskId}`)
        .then(res => {
          this.meta.processCode = res.code

          if (res.code === RESPONSE_CODE.SUCCSS) {
            this.videoJob.videoUrl = res.msg
            clearInterval(this.meta.rollTimeoutIndex)
            this.meta.rollTimeoutIndex = null
          } else if (res.code === RESPONSE_CODE.ERROR) {
            // this._errorTip('资源获取失败')
          }
          if (res.code === 204) {
            this.rollSchedule()
          }
        })
        .catch(() => {
          // this._errorTip('资源获取失败')
        })
    },
    rollSchedule() {
      this.meta.rollTimeoutIndex = setTimeout(async() => {
        this.schedule(this.meta.jobId)
      }, 2000)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload_contain {
  margin-top: 20px;
}
ul {
  list-style: none;
}

.new {
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  flex-direction: column;

  .title,
  .content {
    width: 100%;
    box-sizing: border-box;
    font-size: 14px;
    padding: 5px;
    border-radius: 4px;
    line-height: 1.2em;
    border: 1px solid #c4c4c4;
    outline: none;
  }
  .content-box {
    position: relative;

    .content {
      margin-top: 10px;
      min-height: 200px;
    }

    .wordlimit {
      position: absolute;
      bottom: 20px;
      right: 20px;
      color: #818181;
    }
  }

  .button-box {
    display: flex;
  }
  .submit {
    flex: 1 1 auto;
    background-color: rgb(49, 98, 233);
    border-radius: 4px;
    color: #fff;
    font-size: 20px;
    padding: 4px;
    margin: 0 10px;
    border: none;
    cursor: pointer;
  }
  .video-box {
    display: flex;
    justify-content: center;
    flex: 1 1 auto;
    height: 500px;
    padding: 10px;

    video {
      height: 100%;
      box-shadow: 3px 2px 7px #777;
    }
  }
}
</style>
